/*******************************************************************************
*
* Lord's JS library
*
* Набор рукописных функций для нужд движка
*
* @package Basic
* @author Игорь Будасов aka Lord, web.codr@gmail.com
*
*******************************************************************************/

$('#tip').bt();
/**
 * Функция для скрытия и отображения специальной панельки меню
 */

$(document).ready(function() {
    $(".trigger").click(function(){
        $(".panel").toggle("fast");
        $(this).toggleClass("active");
        return false;
    });
});

/*----------------------------------------------------------------------------*/

$(document).ready(function() {

var id = "#a_0_0_0_0";

$('#level_0 ul').hide();

$(id).parentsUntil().show();


	for(var i = 0; i <= 5; i++) {
	$('#level_' + i + ' > li').click(function() {
		if(false == $(this).next().is(':visible'))
		{
			$('#level_' + i + ' > ul').slideUp(300);
		}
		$(this).next().slideToggle(300);
	});
	}
$('li').click(function (event)
{
    var tmp = $(this).next('ul :has("li")');

        if (tmp.length != 0)
        {
            event.preventDefault();
        }
});

});

/*----------------------------------------------------------------------------*/

/**
* Функция  для автоматической генерации
* части URL-адреса страницы товара в магазине
*/

$(document).ready(function() {
	$("#url").focus(function () {
		var goodName = $("#name").val();
		var goodCode = $("#code").val();
		$("#url").val(function(){
			var goodUrl = (goodCode)
						? goodName +"-"+ goodCode
						: goodName;
			goodUrl = goodUrl.toLowerCase();
			goodUrl = goodUrl.replace(/ /gi, "-");
			goodUrl = goodUrl.replace(/[^a-zA-Z0-9-]/g, "");
			goodUrl = goodUrl.replace(/-{1,}/g, "-");
			goodUrl = goodUrl.replace(/^-/g, "");
			goodUrl = goodUrl.replace(/-$/g, "");
			return goodUrl;
		});
	});
})

/*----------------------------------------------------------------------------*/

/**
* Функция  для автоматического заполнения некоторых полей формы
* при добавлении товара
*/

$(document).ready(function() {

	$("#name").blur(function () {
		var goodName = $("#name").val();
		$("#code").val(goodName);
		$("#seo_title").val(goodName);
		$("#seo_keywords").val(goodName+' купить, '+goodName+' описание, '+goodName+' отзывы, '+goodName+' видео, '+goodName+' аксессуары');
		$("#seo_description").val(goodName+' купить, '+goodName+' описание, '+goodName+' отзывы, '+goodName+' видео, '+goodName+' аксессуары');
	});

})

/*----------------------------------------------------------------------------*/

/**
* Функция  для очистки поля поиска при фокусе на нем
*/

$(document).ready(function() {
	var text = 'Что-нибудь ищите?';
	$("#query").val(text);
	$("#query").css('border', 'none');
	$("#query").focus(function () {
			$("#query").val('');
	});
	$("#query").blur(function () {
			$("#query").val(text);
	});
})

/*----------------------------------------------------------------------------*/

/**
* Функция  для отработки эдитора
* "bold italic underline strikethrough subscript superscript | font size " +
* "style | color highlight removeformat | bullets numbering | outdent " +
* "indent | alignleft center alignright justify | undo redo | " +
* "rule image link unlink | cut copy paste pastetext | print html",
*/

$(document).ready(function() {
	$.cleditor.defaultOptions.width = 430;
	//$.cleditor.defaultOptions.height = 200;
	$.cleditor.defaultOptions.controls =
		"bold italic |  " +
		" color highlight removeformat | bullets numbering  " +
		" | alignleft center alignright justify  | " +
		"image link unlink | pastetext |  html";
	$("#ckeditor1").cleditor()[0];
	$("#ckeditor2").cleditor()[0];
});

/*----------------------------------------------------------------------------*/

/**
* Функция  для тултипа
*/

$(function() {
	$('#tooltiper a').tooltip({
		track: true,
		delay: 0,
		showURL: false,
		fade: 200
	});
});

/*----------------------------------------------------------------------------*/

/**
* Функция  для обработки лайтбокса
*/

$(function() {

	// Select all links in object with gallery ID
	$('.item-left-column a').lightBox();

});

/*----------------------------------------------------------------------------*/

/**
* Код  для обработки таббера на странице товара
*/
$(function () {

	// получаем массив контейнеров
	var tabContainers = $('div.tabs > div');

	// прячем все, кроме первого
	tabContainers.hide().filter(':first').show();

	// далее обрабатывается клик по вкладке
	$('div.tabs ul.tabNavigation a').click(function () {

		// прячем все табы
		tabContainers.hide();

		// показываем содержимое текущего
		tabContainers.filter(this.hash).show();

		// у всех убираем класс 'selected'
		$('div.tabs ul.tabNavigation a').removeClass('selected');

		// текушей вкладке добавляем класс 'selected'
		$(this).addClass('selected');
		return false;

	}).filter(':first').click();
});

/*----------------------------------------------------------------------------*/

/**
* Создание нового объекта XMLHttpRequest для общения с Web-сервером
*/

var xmlHttp = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try
{
	xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
	try
	{
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	catch (e2)
	{
		xmlHttp = false;
	}
}
@end @*/

if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
	xmlHttp = new XMLHttpRequest();
}

/*----------------------------------------------------------------------------*/

/**
* Функция для добавления товара в корзину
* Параметром принимает айдишник товара, который добавлять
*/


function storeCartAdd(id) {
	$.ajax({
		type: "GET",
		dataType: "html",
		url: "/store/cart/add/id/" + escape(id),
		success: function(data) {
			$('#plate-cart').html(data);
		}
	});
}

/*----------------------------------------------------------------------------*/

/**
* Функция для удаления товара из корзины
* Параметром принимает айдишник товара
*/

function storeCartDelete(id) {
	$.ajax({
		url: "/store/cart/delete/id/" + escape(id),
		success: function(data) {
			$('#plate-cart').html(data);
			$('.bt-content').html($('#cart-content').html());
			$('.bt-wrapper').fadeOut('slow');
		}
	});
}

/*----------------------------------------------------------------------------*/

/**
* Функция для добавления товара к сравнению.
* Параметром принимает айдишник товара, который добавить
*/

function storeCompareAdd(id) {
	$.ajax({
		type: "GET",
		dataType: "html",
		url: "/store/compare/add/id/" + escape(id),
		success: function(data) {
			$('#plate-compare').html(data);
		}
	});
}

/*----------------------------------------------------------------------------*/

/**
* Функция для удаления товара из списка товаров для сравнения.
* Параметром принимает айдишник товара
*/

function storeCompareDelete(id) {
	$.ajax({
		url: "/store/compare/delete/id/" + escape(id),
		success: function(data) {
			$('#plate-compare').html(data);
			$('.bt-compare').html($('#compare-content').html());
			$('.bt-wrapper').fadeOut('slow');
		}
	});
}

/*----------------------------------------------------------------------------*/

/**
* Функция для добавления товара в список желаемых товаров, вишлист.
* Параметром принимает айдишник товара, который добавить
*/

function storeWishlistAdd(id) {
	$.ajax({
		type: "GET",
		dataType: "html",
		url: "/store/wishlist/add/id/" + escape(id),
		success: function(data) {
			$('#plate-wishlist').html(data);
		}
	});
}

/*----------------------------------------------------------------------------*/

/**
* Функция для удаления товара из списка желаемых товаров, вишлиста.
* Параметром принимает айдишник товара
*/

function storeWishlistDelete(id) {
	$.ajax({
		url: "/store/wishlist/delete/id/" + escape(id),
		success: function(data) {
			$('#plate-wishlist').html(data);
			$('.bt-wishlist').html($('#wishlist-content').html());
			$('.bt-wrapper').fadeOut('slow');
		}
	});
}

/*----------------------------------------------------------------------------*/

/**
 * Функция для скрывания/отображения какого-нибудь дива
 *
 * Юзать например так:
 * <a  onclick="myToggle(div_id);return false;">link</a>
 * <div id="div_id"  style="display: none;">some content</div>
 */

function myToggle(obj) {
	if(document.getElementById(obj).style.display == 'block') {
		document.getElementById(obj).style.display = 'none';
	}
	else {
		document.getElementById(obj).style.display='block';
	}
}

/*----------------------------------------------------------------------------*/

/**
 *  JS-TrackBar
 *
 *   Copyright (C) 2008 by Alexander Burtsev - webew.ru
 *   and abarmot - http://abarmot.habrahabr.ru/
 *   desing: Светлана Соловьева - http://my.mail.ru/bk/concur/
 *
 *  This code is a public domain.
 */

var trackbar = { // NAMESPACE
	archive : {},
	getObject : function(id) {
		if (typeof this.archive[id] == "undefined") {
			this.archive[id] = new this.hotSearch(id);
		}
		return this.archive[id];
	}
};

trackbar.hotSearch = function(id) { // Constructor
	// Vars
	this.id = id;

	this.leftWidth = 0; // px
	this.rightWidth = 0; // px
	this.width = 0; // px
	this.intervalWidth = 0; // px

	this.leftLimit = 0;
	this.leftValue = 0;
	this.rightLimit = 0;
	this.rightValue = 0;
	this.valueInterval = 0;
	this.widthRem = 6;
	this.valueWidth = 0;
	this.roundUp = 0;

	this.x0 = 0; this.y0 = 0;
	this.blockX0 = 0;
	this.rightX0 = 0;
	this.leftX0 = 0;
	// Flags
	this.dual = true;
	this.moveState = false;
	this.moveIntervalState = false;
	this.debugMode = false;
	this.clearLimits = false;
	this.clearValues = false;
	this.nodeInit = false;
	// Handlers
	this.onMove = null;
	// Nodes
	this.leftBlock = null;
	this.rightBlock = null;
	this.leftBegun = null;
	this.rightBegun = null;
	this.centerBlock = null;
	this.itWasMove = false;
}

trackbar.hotSearch.prototype = {
// Const
	ERRORS : {
		1 : "Ошибка при инициализации объекта",
		2 : "Левый бегунок не найден",
		3 : "Правый бегунок не найден",
		4 : "Левая область ресайза не найдена",
		5 : "Правая область ресайза не найдена",
		6 : "Не задана ширина области бегунка",
		7 : "Не указано максимальное изменяемое значение",
		8 : "Не указана функция-обработчик значений",
		9 : "Не указана область клика"
	},
	LEFT_BLOCK_PREFIX : "leftBlock_",
	RIGHT_BLOCK_PREFIX : "rightBlock_",
	LEFT_BEGUN_PREFIX : "leftBegun_",
	RIGHT_BEGUN_PREFIX : "rightBegun_",
	CENTER_BLOCK_PREFIX : "centerBlock_",
// Methods
	// Default
	gebi : function(id) {
		return document.getElementById(id);
	},
	addHandler : function(object, event, handler, useCapture) {
		if (object.addEventListener) {
			object.addEventListener(event, handler, useCapture ? useCapture : false);
		} else if (object.attachEvent) {
			object.attachEvent('on' + event, handler);
		} else alert(this.errorArray[9]);
	},
	defPosition : function(event) {
		var x = y = 0;
		if (document.attachEvent != null) {
			x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
			y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
		}
		if (!document.attachEvent && document.addEventListener) { // Gecko
			x = event.clientX + window.scrollX;
			y = event.clientY + window.scrollY;
		}
		return {x:x, y:y};
	},
	absPosition : function(obj) {
		var x = y = 0;
		while(obj) {
			x += obj.offsetLeft;
			y += obj.offsetTop;
			obj = obj.offsetParent;
		}
		return {x:x, y:y};
	},
	/*
		Method domReady - Copyright http://ajaxian.com/
		More fun with DOMContentLoaded
		http://ajaxian.com/archives/more-fun-with-domcontentloaded
	*/
	domReady : function(i) {
		var u =navigator.userAgent;
		var e=/*@cc_on!@*/false;
		var st = setTimeout;
		if (/webkit/i.test(u)) {
			st(
				function() {
					var dr=document.readyState;
					if(dr=="loaded"||dr=="complete"){
						i()
					} else {
						st(arguments.callee,10);
					}
				},
				10
			);
		} else if ((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))) {
			document.addEventListener("DOMContentLoaded", i, false);
		} else if (e) {(
			function(){
				var t=document.createElement('doc:rdy');
				try {
					t.doScroll('left');
					i();
					t=null;
				} catch(e) {
					st(arguments.callee,0);
				}
			})();
		} else {
			window.onload=i;
		}
	},
	// Common
	debug : function(keys) {
		if (!this.debugMode) return;
		var mes = "";
		for (var i = 0; i < keys.length; i++) mes += this.ERRORS[keys[i]] + " : ";
		mes = mes.substring(0, mes.length - 3);
		alert(mes);
	},
	init : function(hash, node) {
		if (typeof node != "undefined" && !this.nodeInit) {
			this.nodeInit = true;
			var _this = this;
			this.domReady(
				function() {_this.init(hash, node)}
			);
			return;
		}
		if (typeof node == "string") node = this.gebi(node);
		else node = false;
		try {
			this.dual = typeof hash.dual != "undefined" ? !!hash.dual : this.dual;
			this.leftLimit = hash.leftLimit || this.leftLimit;
			this.rightLimit = hash.rightLimit || this.rightLimit;
			this.width = hash.width || this.width;
			this.onMove = hash.onMove || this.onMove;
			this.clearLimits = hash.clearLimits || this.clearLimits;
			this.clearValues = hash.clearValues || this.clearValues;
			this.roundUp = hash.roundUp || this.roundUp;
			// HTML Write
			var code = '<table' + (this.width ? ' style="width:'+this.width+'px;"' : '') + 'class="trackbar" onSelectStart="return false;">\
				<tr>\
					<td class="l"><div id="leftBlock_' + this.id + '"><span></span><span class="limit"></span><img id="leftBegun_' + this.id + '" ondragstart="return false;" src="/design/images/trackbar/b_l.gif" width="5" height="17" alt="" /></div></td>\
					<td class="c" id="centerBlock_' + this.id + '"></td>\
					<td class="r"><div id="rightBlock_' + this.id + '"><span></span><span class="limit"></span><img id="rightBegun_' + this.id + '" ondragstart="return false;" src="/design/images/trackbar/b_r.gif" width="5" height="17" alt="" /></div></td>\
				</tr>\
			</table>';
			if (node) node.innerHTML = code;
			else document.write(code)
			// Is all right?
			if (this.onMove == null) {
				this.debug([1,8]);
					return;
			}
			// ---
			this.leftBegun = this.gebi(this.LEFT_BEGUN_PREFIX + this.id);
			if (this.leftBegun == null) {
				this.debug([1,2]);
					return;
			}
			this.rightBegun = this.gebi(this.RIGHT_BEGUN_PREFIX + this.id);
			if (this.rightBegun == null) {
				this.debug([1,3]);
					return;
			}
			this.leftBlock = this.gebi(this.LEFT_BLOCK_PREFIX + this.id);
			if (this.leftBlock == null) {
				this.debug([1,4]);
					return;
			}
			this.rightBlock = this.gebi(this.RIGHT_BLOCK_PREFIX + this.id);
			if (this.rightBlock == null) {
				this.debug([1,5]);
					return;
			}
			this.centerBlock = this.gebi(this.CENTER_BLOCK_PREFIX + this.id);
			if (this.centerBlock == null) {
				this.debug([1,9]);
					return;
			}
			// ---
			if (!this.width) {
				this.debug([1,6]);
					return;
			}
			if (!this.rightLimit) {
				this.debug([1,7]);
					return;
			}
			// Set default
			this.valueWidth = this.width - 2 * this.widthRem;
			this.rightValue = hash.rightValue || this.rightLimit;
			this.leftValue = hash.leftValue || this.leftLimit;
			if (!this.dual) this.rightValue = this.leftValue;
			this.valueInterval = this.rightLimit - this.leftLimit;
			this.leftWidth = parseInt((this.leftValue - this.leftLimit) / this.valueInterval * this.valueWidth) + this.widthRem;
			this.rightWidth = this.valueWidth - parseInt((this.rightValue - this.leftLimit) / this.valueInterval * this.valueWidth) + this.widthRem;
			// Set limits
			if (!this.clearLimits) {
				this.leftBlock.firstChild.nextSibling.innerHTML = this.leftLimit;
				this.rightBlock.firstChild.nextSibling.innerHTML = this.rightLimit;
			}
			// Do it!
			this.setCurrentState();
			this.onMove();
			// Add handers
			var _this = this;
			this.addHandler (
				document,
				"mousemove",
				function(evt) {
					if (_this.moveState) _this.moveHandler(evt);
					if (_this.moveIntervalState) _this.moveIntervalHandler(evt);
				}
			);
			this.addHandler (
				document,
				"mouseup",
				function() {
					_this.moveState = false;
					_this.moveIntervalState = false;
				}
			);
			this.addHandler (
				this.leftBegun,
				"mousedown",
				function(evt) {
					evt = evt || window.event;
					if (evt.preventDefault) evt.preventDefault();
					evt.returnValue = false;
					_this.moveState = "left";
					_this.x0 = _this.defPosition(evt).x;
					_this.blockX0 = _this.leftWidth;
				}
			);
			this.addHandler (
				this.rightBegun,
				"mousedown",
				function(evt) {
					evt = evt || window.event;
					if (evt.preventDefault) evt.preventDefault();
					evt.returnValue = false;
					_this.moveState = "right";
					_this.x0 = _this.defPosition(evt).x;
					_this.blockX0 = _this.rightWidth;
				}
			);
			this.addHandler (
				this.centerBlock,
				"mousedown",
				function(evt) {
					evt = evt || window.event;
					if (evt.preventDefault) evt.preventDefault();
					evt.returnValue = false;
					_this.moveIntervalState = true;
					_this.intervalWidth = _this.width - _this.rightWidth - _this.leftWidth;
					_this.x0 = _this.defPosition(evt).x;
					_this.rightX0 = _this.rightWidth;
					_this.leftX0 = _this.leftWidth;
				}
			),
			this.addHandler (
				this.centerBlock,
				"click",
				function(evt) {
					if (!_this.itWasMove) _this.clickMove(evt);
					_this.itWasMove = false;
				}
			);
			this.addHandler (
				this.leftBlock,
				"click",
				function(evt) {
					if (!_this.itWasMove)_this.clickMoveLeft(evt);
					_this.itWasMove = false;
				}
			);
			this.addHandler (
				this.rightBlock,
				"click",
				function(evt) {
					if (!_this.itWasMove)_this.clickMoveRight(evt);
					_this.itWasMove = false;
				}
			);
		} catch(e) {this.debug([1]);}
	},
	clickMoveRight : function(evt) {
		evt = evt || window.event;
		if (evt.preventDefault) evt.preventDefault();
		evt.returnValue = false;
		var x = this.defPosition(evt).x - this.absPosition(this.rightBlock).x;
		var w = this.rightBlock.offsetWidth;
		if (x <= 0 || w <= 0 || w < x || (w - x) < this.widthRem) return;
		this.rightWidth = (w - x);
		this.rightCounter();

		this.setCurrentState();
		this.onMove();
	},
	clickMoveLeft : function(evt) {
		evt = evt || window.event;
		if (evt.preventDefault) evt.preventDefault();
		evt.returnValue = false;
		var x = this.defPosition(evt).x - this.absPosition(this.leftBlock).x;
		var w = this.leftBlock.offsetWidth;
		if (x <= 0 || w <= 0 || w < x || x < this.widthRem) return;
		this.leftWidth = x;
		this.leftCounter();

		this.setCurrentState();
		this.onMove();
	},
	clickMove : function(evt) {
		evt = evt || window.event;
		if (evt.preventDefault) evt.preventDefault();
		evt.returnValue = false;
		var x = this.defPosition(evt).x - this.absPosition(this.centerBlock).x;
		var w = this.centerBlock.offsetWidth;
		if (x <= 0 || w <= 0 || w < x) return;
		if (x >= w / 2) {
			this.rightWidth += (w - x);
			this.rightCounter();
		} else {
			this.leftWidth += x;
			this.leftCounter();
		}
		this.setCurrentState();
		this.onMove();
	},
	setCurrentState : function() {
		this.leftBlock.style.width = this.leftWidth + "px";
		if (!this.clearValues) this.leftBlock.firstChild.innerHTML = (!this.dual && this.leftWidth > this.width / 2) ? "" : this.leftValue;
		if(!this.dual) {
			var x = this.leftBlock.firstChild.offsetWidth;
			this.leftBlock.firstChild.style.right = (this.widthRem * (1 - 2 * (this.leftWidth - this.widthRem) / this.width) - ((this.leftWidth - this.widthRem) * x / this.width)) + 'px';
		}
		this.rightBlock.style.width = this.rightWidth + "px";
		if (!this.clearValues) this.rightBlock.firstChild.innerHTML = (!this.dual && this.rightWidth >= this.width / 2) ? "" : this.rightValue;
		if(!this.dual) {
			var x = this.rightBlock.firstChild.offsetWidth;
			this.rightBlock.firstChild.style.left = (this.widthRem * (1 - 2 * (this.rightWidth - this.widthRem) / this.width) - ((this.rightWidth - this.widthRem) * x / this.width)) + 'px';
		}
	},
	moveHandler : function(evt) {
		this.itWasMove = true;
		evt = evt || window.event;
		if (evt.preventDefault) evt.preventDefault();
		evt.returnValue = false;
		if (this.moveState == "left") {
			this.leftWidth = this.blockX0 + this.defPosition(evt).x - this.x0;
			this.leftCounter();
		}
		if (this.moveState == "right") {
			this.rightWidth = this.blockX0 + this.x0 - this.defPosition(evt).x;
			this.rightCounter();
		}
		this.setCurrentState();
		this.onMove();
	},
	moveIntervalHandler : function(evt) {
		this.itWasMove = true;
		evt = evt || window.event;
		if (evt.preventDefault) evt.preventDefault();
		evt.returnValue = false;
		var dX = this.defPosition(evt).x - this.x0;
		if (dX > 0) {
			this.rightWidth = this.rightX0 - dX > this.widthRem ? this.rightX0 - dX : this.widthRem;
			this.leftWidth = this.width - this.rightWidth - this.intervalWidth;
		} else {
			this.leftWidth = this.leftX0 + dX > this.widthRem ? this.leftX0 + dX : this.widthRem;
			this.rightWidth = this.width - this.leftWidth - this.intervalWidth;
		}
		this.rightCounter();
		this.leftCounter();
		this.setCurrentState();
		this.onMove();
	},
	updateRightValue : function(rightValue) {
		try {
			this.rightValue = parseInt(rightValue);
			this.rightValue = this.rightValue < this.leftLimit ? this.leftLimit : this.rightValue;
			this.rightValue = this.rightValue > this.rightLimit ? this.rightLimit : this.rightValue;
			if (this.dual) {
				this.rightValue = this.rightValue < this.leftValue ? this.leftValue : this.rightValue;
			} else this.leftValue = this.rightValue;
			this.rightWidth = this.valueWidth - parseInt((this.rightValue - this.leftLimit) / this.valueInterval * this.valueWidth) + this.widthRem;
			this.rightWidth = isNaN(this.rightWidth) ? this.widthRem : this.rightWidth;
			if (!this.dual) this.leftWidth = this.width - this.rightWidth;
			this.setCurrentState();
		} catch(e) {}
	},
	rightCounter : function() {
		if (this.dual) {
			this.rightWidth = this.rightWidth > this.width - this.leftWidth ? this.width - this.leftWidth : this.rightWidth;
			this.rightWidth = this.rightWidth < this.widthRem ? this.widthRem : this.rightWidth;
			this.rightValue = this.leftLimit + this.valueInterval - parseInt((this.rightWidth - this.widthRem) / this.valueWidth * this.valueInterval);
			if (this.roundUp) this.rightValue = parseInt(this.rightValue / this.roundUp) * this.roundUp;
			if (this.leftWidth + this.rightWidth >= this.width) this.rightValue = this.leftValue;
		} else {
			this.rightWidth = this.rightWidth > (this.width - this.widthRem) ? this.width - this.widthRem : this.rightWidth;
			this.rightWidth = this.rightWidth < this.widthRem ? this.widthRem : this.rightWidth;
			this.leftWidth = this.width - this.rightWidth;
			this.rightValue = this.leftLimit + this.valueInterval - parseInt((this.rightWidth - this.widthRem) / this.valueWidth * this.valueInterval);
			if (this.roundUp) this.rightValue = parseInt(this.rightValue / this.roundUp) * this.roundUp;
			this.leftValue = this.rightValue;
		}
	},
	updateLeftValue : function(leftValue) {
		try {
			this.leftValue = parseInt(leftValue);
			this.leftValue = this.leftValue < this.leftLimit ? this.leftLimit : this.leftValue;
			this.leftValue = this.leftValue > this.rightLimit ? this.rightLimit : this.leftValue;
			if (this.dual) {
				this.leftValue = this.rightValue < this.leftValue ? this.rightValue : this.leftValue;
			} else this.rightValue = this.leftValue;
			this.leftWidth = parseInt((this.leftValue - this.leftLimit) / this.valueInterval * this.valueWidth) + this.widthRem;
			this.leftWidth = isNaN(this.leftWidth) ? this.widthRem : this.leftWidth;
			if (!this.dual) this.rightWidth = this.width - this.leftWidth;
			this.setCurrentState();
		} catch(e) {}
	},
	leftCounter : function() {
		if (this.dual) {
			this.leftWidth = this.leftWidth > this.width - this.rightWidth ? this.width - this.rightWidth : this.leftWidth;
			this.leftWidth = this.leftWidth < this.widthRem ? this.widthRem : this.leftWidth;
			this.leftValue = this.leftLimit + parseInt((this.leftWidth - this.widthRem) / this.valueWidth * this.valueInterval);
			if (this.roundUp) this.leftValue = parseInt(this.leftValue / this.roundUp) * this.roundUp;
			if (this.leftWidth + this.rightWidth >= this.width) this.leftValue = this.rightValue;
		} else {
			this.leftWidth = this.leftWidth > (this.width - this.widthRem) ? this.width - this.widthRem : this.leftWidth;
			this.leftWidth = this.leftWidth < this.widthRem ? this.widthRem : this.leftWidth;
			this.rightWidth = this.width - this.leftWidth;
			this.leftValue = this.leftLimit + parseInt((this.leftWidth - this.widthRem) / this.valueWidth * this.valueInterval);
			if (this.roundUp) this.leftValue = parseInt(this.leftValue / this.roundUp) * this.roundUp;
			this.rightValue = this.leftValue;
		}
	}
}

/*----------------------------------------------------------------------------*/

/*!
 * Tiny Carousel 1.8
 * http://www.baijs.nl/tinycarousel
 *
 * Copyright 2010, Maarten Baijs
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/gpl-2.0.php
 *
 * Date: 10 / 11 / 2010
 * Depends on library: jQuery
 */

$(document).ready(function() {
    $('#slider-code').tinycarousel({ pager: true, interval: true  });
});

(function($) {
    $.fn.tinycarousel = function(options) {
        var defaults = {
            start: 2, // where should the carousel start?
            display: 1, // how many blocks do you want to move at 1 time?
            axis: 'x', // vertical or horizontal scroller? ( x || y ).
            controls: true, // show left and right navigation buttons.
            pager: false, // is there a page number navigation present?
            interval: false, // move to another block on intervals.
            intervaltime: 3000, // interval time in milliseconds.
            rewind: false, // If interval is true and rewind is true it will play in reverse if the last slide is reached.
            animation: true, // false is instant, true is animate.
            duration: 300, // how fast must the animation move in ms?
            callback: null // function that executes after every move
        };
        var options = $.extend(defaults, options);

        var oSlider = $(this);
        var oViewport = $('.viewport:first', oSlider);
        var oContent = $('.overview:first', oSlider);
        var oPages = oContent.children();
        var oBtnNext = $('.next:first', oSlider);
        var oBtnPrev = $('.prev:first', oSlider);
        var oPager = $('.slider-navigation:first', oSlider);
        var iPageSize, iSteps, iCurrent, oTimer, bPause, bForward = true, bAxis = options.axis == 'x';

        return this.each(function() {
            initialize();
        });
        function initialize() {
            iPageSize = bAxis ? $(oPages[0]).outerWidth(true) : $(oPages[0]).outerHeight(true);
            var iLeftover = Math.ceil(((bAxis ? oViewport.outerWidth() : oViewport.outerHeight()) / (iPageSize * options.display)) -1);
            iSteps = Math.max(1, Math.ceil(oPages.length / options.display) - iLeftover);
            iCurrent = Math.min(iSteps, Math.max(1, options.start)) -2;
            oContent.css(bAxis ? 'width' : 'height', (iPageSize * oPages.length));
            move(1);
            setEvents();
        }
        function setEvents() {
            if(options.controls && oBtnPrev.length > 0 && oBtnNext.length > 0){
                oBtnPrev.click(function(){move(-1); return false;});
                oBtnNext.click(function(){move( 1); return false;});
            }
            if(options.interval) {
                oSlider.hover(function(){clearTimeout(oTimer); bPause = true},function(){bPause = false; setTimer();});
            }
            if(options.pager && oPager.length > 0) {
                $('a',oPager).click(setPager);
            }
        }
        function setButtons() {
            if(options.controls){
                oBtnPrev.toggleClass('disable', !(iCurrent > 0));
                oBtnNext.toggleClass('disable', !(iCurrent +1 < iSteps));
            }
            if(options.pager) {
                var oNumbers = $('.pagenum', oPager);
                oNumbers.removeClass('active');
                $(oNumbers[iCurrent]).addClass('active');
            }
        }
        function setPager(oEvent) {
            if($(this).hasClass('pagenum')) {
                iCurrent = parseInt(this.rel) -1;
                move(1);
            }
            return false;
        }
        function setTimer() {
            if(options.interval && !bPause) {
                clearTimeout(oTimer);
                oTimer = setTimeout(function() {
                    iCurrent = !options.rewind && (iCurrent +1 == iSteps) ? -1 : iCurrent;
                    bForward = iCurrent +1 == iSteps ? false : iCurrent == 0 ? true : bForward;
                    move((options.rewind ? (bForward ? 1 : -1) : 1));
                }, options.intervaltime);
            }
        }
        function move(iDirection) {
            if(iCurrent + iDirection > -1 && iCurrent + iDirection < iSteps) {
                iCurrent += iDirection;
                var oPosition = {};
                oPosition[bAxis ? 'left' : 'top'] = -(iCurrent * (iPageSize * options.display));
                oContent.animate(oPosition,{
                    queue: false,
                    duration: options.animation ? options.duration : 0,
                    complete: function() {
                        if(typeof options.callback == 'function')
                        options.callback.call(this, oPages[iCurrent], iCurrent);
                    }
                });
                setButtons();
                setTimer();
            }
        }
    };
})(jQuery);

/*----------------------------------------------------------------------------*/


